'use client'

import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'

// 默认值
const DEFAULT_MODEL_NAME = '/data/hpc/home/yue.wang04/models/qvl/Qwen2.5-VL-72B-Instruct'
const DEFAULT_PROMPT = `You are an expert image analysis AI. Analyze this image with EXTREME PRECISION and identify ALL distinct visual layers including text, shapes, and images.

CRITICAL REQUIREMENTS:
1. Provide EXACT pixel coordinates for position {x, y, width, height}
2. Identify EVERY text element separately (headlines, body text, captions, labels, buttons)
3. Detect ALL shapes (rectangles, circles, lines, icons, backgrounds)
4. Identify ALL image elements (photos, illustrations, logos, icons)

For TEXT layers, include:
- Exact text content
- Precise position and dimensions
- Font size, family, weight, style
- Color, alignment, line height, letter spacing
- Confidence score and language

For IMAGE layers, include:
- Detailed description of image content
- Exact position and dimensions
- Border radius, box shadow, opacity, rotation
- Confidence score and image type (photo/illustration/icon)

For SHAPE layers, include:
- Description (rectangle background, circle button, line divider, etc.)
- Exact position and dimensions
- Background color, border properties, border radius
- Box shadow and opacity
- Confidence score

Order layers from background to foreground. Be as precise as possible with measurements.

Output ONLY valid JSON with this exact TypeScript-like schema (no markdown, no extra text):
{ "layers": [ { "type": "text" | "image" | "shape", "content": string, "position": { "x": number, "y": number, "width": number, "height": number }, "style": { "fontSize"?: string, "fontFamily"?: string, "fontWeight"?: string, "fontStyle"?: string, "lineHeight"?: string, "letterSpacing"?: string, "textAlign"?: string, "textDecoration"?: string, "color"?: string, "backgroundColor"?: string, "borderColor"?: string, "borderWidth"?: string, "borderRadius"?: string, "boxShadow"?: string, "textShadow"?: string, "opacity"?: string, "padding"?: string, "margin"?: string, "rotation"?: string }, "metadata": { "confidence": number, "language"?: string, "estimatedFont"?: string, "imageType"?: string } } ] }`

// 本地存储的键
const STORAGE_KEY_MODEL = 'vllm_model_name'
const STORAGE_KEY_PROMPT = 'vllm_prompt'

interface SettingsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export interface SettingsConfig {
  modelName: string
  prompt: string
}

// 从本地存储加载配置
export function loadSettings(): SettingsConfig {
  if (typeof window === 'undefined') {
    return {
      modelName: DEFAULT_MODEL_NAME,
      prompt: DEFAULT_PROMPT,
    }
  }

  const modelName = localStorage.getItem(STORAGE_KEY_MODEL) || DEFAULT_MODEL_NAME
  const prompt = localStorage.getItem(STORAGE_KEY_PROMPT) || DEFAULT_PROMPT

  return { modelName, prompt }
}

// 保存配置到本地存储
export function saveSettings(config: SettingsConfig) {
  if (typeof window === 'undefined') return

  localStorage.setItem(STORAGE_KEY_MODEL, config.modelName)
  localStorage.setItem(STORAGE_KEY_PROMPT, config.prompt)
}

export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
  const [modelName, setModelName] = useState(DEFAULT_MODEL_NAME)
  const [prompt, setPrompt] = useState(DEFAULT_PROMPT)

  // 加载配置
  useEffect(() => {
    if (open) {
      const settings = loadSettings()
      setModelName(settings.modelName)
      setPrompt(settings.prompt)
    }
  }, [open])

  // 保存设置
  const handleSave = () => {
    saveSettings({ modelName, prompt })
    onOpenChange(false)
  }

  // 重置为默认值
  const handleReset = () => {
    setModelName(DEFAULT_MODEL_NAME)
    setPrompt(DEFAULT_PROMPT)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>设置</DialogTitle>
          <DialogDescription>
            配置 VLLM 模型和 Prompt 参数。这些设置将保存在浏览器本地存储中。
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* VLLM 模型名称 */}
          <div className="space-y-2">
            <Label htmlFor="model-name">VLLM 模型名称</Label>
            <Input
              id="model-name"
              value={modelName}
              onChange={(e) => setModelName(e.target.value)}
              placeholder={DEFAULT_MODEL_NAME}
              className="font-mono text-sm"
            />
            <p className="text-xs text-muted-foreground">
              模型路径或名称，用于图像分析
            </p>
          </div>

          {/* Prompt */}
          <div className="space-y-2">
            <Label htmlFor="prompt">Prompt 提示词</Label>
            <Textarea
              id="prompt"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder={DEFAULT_PROMPT}
              className="font-mono text-sm min-h-[300px]"
            />
            <p className="text-xs text-muted-foreground">
              用于图像分析的提示词，控制 AI 如何分析和提取图层信息
            </p>
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleReset}>
            恢复默认
          </Button>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSave}>
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

